package com.qlylkj.lbk.ui.search

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.qlylkj.lbk.base.BaseViewModel
import com.qlylkj.lbk.model.api.ResultResponse
import com.qlylkj.lbk.model.bean.Company
import com.qlylkj.lbk.model.repository.CompanyRepository

class SearchViewModel: BaseViewModel() {

    private val _uiState = MutableLiveData<SearchUiModel>()
    val uiState: LiveData<SearchUiModel>
        get() = _uiState

    private val companyRepository by lazy { CompanyRepository() }

    private fun emitUiState(
        showError: String? = null,
        companyList: MutableList<Company> = mutableListOf()
    ) {
        val uiModel = SearchUiModel(showError,companyList)
        _uiState.value = uiModel
    }

    data class SearchUiModel(
        val showError: String?,
        val companyList: MutableList<Company>
    )

    fun search(keyword: String){
        launch {
            val result = companyRepository.getCompanyList(keyword)
            if (result is ResultResponse.SuccessEntity) {
                emitUiState(companyList = result.data.records)
            } else if (result is ResultResponse.Error) {
                emitUiState(showError = result.exception.message)
            }
        }
    }
}